package org.igorrogic.jndi_provider;

import com.sun.jndi.rmi.registry.ReferenceWrapper;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import java.rmi.registry.LocateRegistry;
import java.util.Hashtable;

public class ObjectProvider {
    public static void x(){
        Context context = null;
        try {
            Hashtable env = new Hashtable();
            /*env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
            context = new InitialContext(env);*/
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
            System.setProperty(Context.PROVIDER_URL, "rmi://127.0.0.1:3001");
            context = new InitialContext();
            //Person jordan = (Person) context.lookup("jordan");
            //System.out.println("jordan = " + jordan.getName());
        } catch (NamingException nex) {
            System.out.println("Initial context couldn't have been created.");
            nex.printStackTrace();
        } finally {
            try {
                context.close();
            } catch (NamingException nex) {
                System.out.println("Initial context couldn't have been closed.");
                nex.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws Exception{
        Context context = null;
        try {
            Hashtable env = new Hashtable();
            /*env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
            context = new InitialContext(env);*/
            LocateRegistry.createRegistry(3001);

            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");

            System.setProperty(Context.PROVIDER_URL, "rmi://127.0.0.1:3001");
            context = new InitialContext();
            //context.rebind("jordan", new Person("Michael Jordan"));


            Reference aa = new Reference("Personx", "Personx", "http://127.0.0.1:8001/");

            ReferenceWrapper refObjWrapper = new ReferenceWrapper(aa);
            context.rebind("jordanx", refObjWrapper);


            System.out.println("Successfully bound Michael Jordan to jordan.");
        } catch (NamingException nex) {
            System.out.println("Initial context couldn't have been created.");
            nex.printStackTrace();
        } finally {
            try {
                //context.close();
                while(true){}
                //x();
            } catch (Exception nex) {
                System.out.println("Initial context couldn't have been closed.");
                nex.printStackTrace();
            }
        }
    }
}
